<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="物资明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">

                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                             <el-form :model="basicForm" :label-width="formLabelWidth">
                                <el-row>
                                <el-col :span="12">
                                <el-form-item label="计划编号：">
                                    <span>{{ basicForm.temporaryDemandPlanBillNo }}</span>
                                </el-form-item>
                            </el-col>
                             </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="计划编号：">
                                    <span>{{ basicForm.billNo }}</span>
                                    <el-button class="a"
                                            @click="clickToBill"
                                            >查看</el-button
                                        >
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="年度需用计划：">
                                    <div style="display: flex">
                                                <div >{{basicForm.annualDemandPlanBillNo}}</div>

                                           <el-button class="a"
                                            @click="clickToYearNeedPlan"
                                            >查看</el-button
                                        >
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="采购方式：">
                                    <span>
                                                {{
                                                    basicForm.businessType == 0
                                                        ? '自购'
                                                        : '租赁'
                                                }}
                                            </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="变更日期：">
                                   <span>{{
                                                basicForm.planDate
                                            }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="要签合同：">
                                      <span>
                                                {{
                                                    basicForm.isSignContract==1?"是":'否'
                                                }}
                                            </span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="计划金额（元）：">
                                            <span>{{ basicForm.amount }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
 <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税率%："
                                            prop="taxRate"
                                        >

                                            <span>{{basicForm.taxRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税额："
                                            prop="taxAmount"
                                        >
                                            <span>{{basicForm.taxAmount}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                       <el-col :span="12">
                                        <el-form-item
                                            label="不含税计划金额（元）："
                                            ><span>
                                                {{
                                                    basicForm.amountExcludingTax
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                      <el-col :span="12">
                                <el-form-item label="变更计划金额（元）：">
                                            <span>{{ basicForm.amountChanged }}</span>
                                </el-form-item>
                            </el-col>
                                </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="币种：">
                                           {{ basicForm.currency }}
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="人民币汇率：">
                                    <span>{{ basicForm.rmbRate }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="单据机构：">
                                    <span>{{ basicForm.orgName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="传财务共享：">
                                    <span>{{ basicForm.state }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="备注：">
                                      <span>{{ basicForm.remarks }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币：">
                                    <span>{{ basicForm.baseCurName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="本位币汇率：">
                                    <span>{{
                                        basicForm.baseCurRate
                                    }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="变更期数：">
                                    <span>{{ basicForm.period }}</span>
                                </el-form-item>
                            </el-col>

                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                     <el-form-item
                                    label="填报人："
                                >
                                    <span>{{ basicForm.preparer }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="状态：">
                                         <span>{{ statusLable(basicForm.state) }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                       <el-row v-if="basicForm.state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ basicForm.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{basicForm.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                basicForm.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                basicForm.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                    </el-form>
                        </div>
                    </div>
                    <!-- 物资明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">物资明细</div>
                        <div class="e-table">
                            <!-- <div class="top">
                                <div class="left">
                                       <el-button size="mini" type="primary"
                                        @click="clickYearNeedPlanImport"
                                        >年计划引入</el-button
                                    >
                                    <el-button size="mini" type="primary"
                                        @click="clickBaseImpot"
                                        >基础库引入</el-button
                                    >
                                </div>
                            </div> -->
                         <el-table
                                class="table"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                 default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                 :row-class-name="tableRowClass"
                                 :max-height="$store.state.tableHeight"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"

                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="quantity"
                                    label="数量"
                                    width="100"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="price"
                                    label="单价"
                                    width="100"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="amount"
                                    label="金额"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantityChanged"
                                    width="200"
                                >
                                   <template slot="header">
                                        <div class="tab-header">
                                            需求数量<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                 <template slot-scope="{ row, $index }">
                                        <el-input
                                        v-enter-float2="{
                                            set: row,
                                            key: 'quantityChanged'
                                        }"
                                            v-model="row.quantityChanged"
                                            @input="curStateChange(row)"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="priceChanged"
                                    width="200"
                                >
                                   <template slot="header">
                                        <div class="tab-header">
                                            单价（元）<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                     <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-enter-float="{
                                            set: row,
                                            key: 'priceChanged'
                                            }"
                                            @input="curStateChange(row)"
                                            v-model="row.priceChanged"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amountChanged"
                                    label="金额（元）"
                                    width="200"
                                >
                                   <template slot="header">
                                        <div class="tab-header">
                                            金额（元）<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                <template slot-scope="{row,$index}">
                                    <span v-if="$index>0">
                                        {{
                                            row.amountChanged
                                        }}
                                    </span>
                                </template>
                                </el-table-column>

                                <el-table-column
                                    v-if="lease"
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="200"
                                >

                                </el-table-column>
                                <el-table-column
                                    v-if="lease"

                                    prop="leaseTime"
                                    label="租赁时间"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    v-if="lease"

                                    prop="leaseTimeChanged"
                                    label="租赁时间"
                                    width="200"
                                >
                                <template slot="header">
                                        <div class="tab-header">
                                           租赁时间<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                <template slot-scope="{row, $index }">
                                    <el-input
                                    type="number"
                                    v-model="row.leaseTimeChanged" @input="curStateChange(row)"

                                            v-if="$index > 0"

                                    ></el-input>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    v-if="lease"

                                    prop="startTime"
                                    label="开始使用时间"
                                    width="200"
                                >

                                </el-table-column>
                                <el-table-column
                                    v-if="lease"

                                    prop="endTime"
                                    label="结束使用时间"
                                    width="200"
                                >
                                </el-table-column>

                                   <el-table-column
                                    v-if="lease"

                                    prop="startTimeChanged"
                                    label="开始使用时间"
                                    width="200"
                                >
                                <template slot="header">
                                        <div class="tab-header">
                                            开始使用时间<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                              <template slot-scope="{row, $index }">
                                     <el-date-picker
                                                v-if="$index>0"
                                                type="date"
                                                @chenge="curStateChange(row)"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                v-model="row.startTimeChanged"
                                            ></el-date-picker>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    v-if="lease"

                                    prop="endTimeChanged"
                                    label="结束使用时间"
                                    width="200"
                                >
                                     <template slot="header">
                                        <div class="tab-header">
                                            结束使用时间<span class="tab-heade-icon"
                                                >变</span
                                            >
                                        </div>
                                    </template>
                                  <template slot-scope="{row, $index }">
                                     <el-date-picker
                                                v-if="$index>0"
                                                type="date"
                                                @chenge="curStateChange(row)"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                v-model="row.endTimeChanged"
                                            ></el-date-picker>
                                </template>
                                </el-table-column>
                            </el-table>
                             <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="turnover" isView/>

                    </div>
                    <!-- 审核历史 -->
                   <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6093"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>

                </div>
            </el-tabs>
        </div>

               <div class="buttons">
            <!-- <el-button
                type="primary"
                class="btn-blue"
                @click="submit"
                size="small"
                v-if="statusLable(basicForm.state) !== '已作废' && statusLable(basicForm.state) === '审核中'"
                >保存</el-button> -->
            <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId"    :isPrint="basicForm.state === 2||basicForm.state === 1"/>
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import auditRequest from '@/api/turnover/audit.js'
import { openAppClient, getUuid, showLoading, hideLoading } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'
import dataBaseRequest from '@/api/turnover/dataBase.js'
import planRequest from '@/api/turnover/plan.js'

import ComExaButtons from '@/components/common/exaButtons'
import { exas } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: { AttachComp, ComAuditHistoryIndex, ComExaButtons },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        ...mapState({
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        lease () { //租赁状态
            if (
                this.basicForm.businessType &&
                this.basicForm.businessType == 1
            ) {
                return true
            } else {
                return false
            }
        }

    },

    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'attach', 'auditHistory']
        this.tabArr = arr  //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    created () {
        this.billId = this.$route.query.billid
        this.getCurrentUnitInfo()

        this.getYearNeedPlanList()//年度需用计划列表
        this.getBasicInfo()
        this.turnoverTemporaryDemandPlanChangedFindDtlByBillId()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                'amount': 0,
                'amountChanged': 0,
                'annualDemandPlanBillId': '',
                'annualDemandPlanBillNo': '',
                'baseCurAmt': 0,
                'baseCurAmtChanged': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'businessType': 0,
                'currency': '',
                'currencyId': '',
                'easId': '',
                'isSignContract': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'period': 0,
                'planDate': '',
                'preparer': '',
                'preparerId': '',
                'remarks': '',
                'rmbAmt': 0,
                'rmbAmtChanged': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'state': '',
                'taxAmount': 0,
                'taxRate': 0,
                'temporaryDemandPlanBillId': '',
                'temporaryDemandPlanBillNo': '',
                'workId': '',
                'amountExcludingTax': ''

            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: [],
            },
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            changeTableData: [], //变更信息
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            yearNeedPlanList: [],
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6093,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 6093,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
        }
    },
    methods: {
        ...mapMutations(['setAuditParams']),

        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        turnoverTemporaryDemandPlanChangedFindDtlByBillId () {
            // 获取明细
            planRequest.turnoverTemporaryDemandPlanChangedFindDtlByBillId(this.billId).then(res=>{
                if (res.length > 0) {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        item.type = this.basicForm.businessType
                        item.businessType = this.basicForm.businessType
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })

                    this.detailedTableData = res
                    //明细金额向上汇总到基础表单 不含税计划金额（元）
                    this.collectCount()
                    this.onTaxRate()
                }
            })
        },
        getYearNeedPlanList () {
            this.$Ajax
                .httpPost({
                    url: '/turnover/annualDemandPlan/listByEntity',
                    params: this.query,
                })
                .then(res => {
                    this.yearNeedPlanList = res.list
                })
        },
        //选择币种的事件
        changeCurrency () {
            const obj = this.currencyArr.find(item=>item.kvKey === this.basicForm.currency)
            this.basicForm.currencyId = obj.kvId
        },
        changePlan () {
            const obj = this.yearNeedPlanList.find(item=>item.id === this.basicForm.annualDemandPlanId)
            this.basicForm.annualDemandPlan = obj.number
        },

        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/temporaryDemandPlanChanged/findById',
                    params: {
                        id: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    res.isSignContract === 1 ? res.isSignContract = true : res.isSignContract = false
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                    }

                })
        },
        clickToYearNeedPlan () {
            let billid = this.basicForm.annualDemandPlanBillId
            if (!billid) {
                this.clientPop('err', '请选择年度需用计划！')
                return
            }
            // 客户端弹窗弹出本地页面
            openAppClient(`/yearNeedPlanShow?billid=${billid}&isview=true`, '年度需用计划')
        },
        clickToBill () {
            let billid = this.basicForm.temporaryDemandPlanBillId

            // 客户端弹窗弹出本地页面
            openAppClient(`/momentNeedPlanShow?billid=${billid}&isview=true`, '临时需用计划')
        },
        tableRowClass ({ row }) {
            if (row.oldState == -1) {
                return 'red'
            } else if (row.oldState == 1) {
                return 'green'
            } else if (row.oldState == 2) {
                return 'yellow'
            } else if (row.children) {
                return 'warning-row'
            }
            return ''
        },
        deleteEle (row) {
            row.changeType = -1
            row.oldState = -1
            this.collectCount()
        },
        cancelDel (row) {
            row.changeType = 2
            row.oldState = 0
            this.collectCount()

        },
        /**
         * 审核
         */
        /**
         * 下边几个按钮
         */

        //更新基本信息
        updateBaseInfo () {
            this.basicForm.isSignContract ? this.basicForm.isSignContract = 1 : this.basicForm.isSignContract = 0
            return new Promise((resolve, reject)=>{

                planRequest.turnoverTemporaryDemandPlanChangedUpdate(this.basicForm).then(()=>{
                    this.getBasicInfo() //更新基本信息
                    resolve()
                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                })

            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    planRequest.turnoverTemporaryDemandPlanChangedUpdateDtl(this.detailedTableData).then(()=>{
                        // this.getdtlList() //更新明细
                        resolve()
                    }).catch(err=>{
                        this.setError('detailed')
                        reject(err)
                    })
                }).catch(err=>{
                    this.setError('detailed')
                    reject(err)
                })

            })
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                ]
            }
            const printData = async ()=>{
                showLoading()

                try{
                    const  params =  {
                        'reportTitle': '临时需用计划单', //报表名
                        'orgName': '', //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': '', //单据编码
                        'summaryInfoItems': [ //基本信息
                        ],
                        'tables': [ //表格
                        ]
                    }
                    const formData = this.basicForm
                    // params.reportTitle = formData.contractName
                    params.orgName = formData.orgName
                    params.billNo = formData.billNo
                    const baseInfo = [
                        ['采购方式', formData.businessType == 0 ? '自购'
                            : '租赁', false],
                        ['变更编号', formData.billNo, false],
                        ['计划金额', formData.amountChanged, false],
                        ['原金额', formData.amount, false],
                        ['币种', formData.currency, false],
                        ['传财务共享', formData.state, false],
                        ['备注信息', formData.remarks, true],
                    ]
                    baseInfo.forEach(item=>{
                        const summaryInfoItem = {}
                        summaryInfoItem.label = item[0]
                        summaryInfoItem.value = item[1]
                        summaryInfoItem.isFullRow = item[2]
                        params.summaryInfoItems.push(summaryInfoItem)
                    })
                    let res = await  planRequest.turnoverTemporaryDemandPlanChangedFindDtlByBillId(this.billId)
                    let contractListData = res[0].children

                    const contractList = {
                        'tableTitle': '计划清单',

                        'tableContent': {
                            '物资类别': 'materialClassName',
                            '物资名称': 'materialName',
                            '规格': 'spec',
                            '计量单位': 'unit',
                            '材质': 'texture',
                            '数量': 'quantityChanged',
                            '单价': 'priceChanged',
                            '金额': 'amountChanged',
                            '计时单位': 'timeUnit',
                            '租赁时间': 'leaseTimeChanged',
                            '开始使用时间': 'startTimeChanged',
                            '结束使用时间': 'endTimeChanged',
                        },
                        'tableData': contractListData, //表格数据
                    }
                    const contractList2 = {
                        'tableTitle': '计划清单',

                        'tableContent': {
                            '物资类别': 'materialClassName',
                            '物资名称': 'materialName',
                            '规格': 'spec',
                            '计量单位': 'unit',
                            '材质': 'texture',
                            '数量': 'quantityChanged',
                            '单价': 'priceChanged',
                            '金额': 'amountChanged',
                        },
                        'tableData': contractListData, //表格数据
                    }

                    let getAuditHistory = await  auditRequest.getAuditHistory(this.auditParams)
                    const auditHistoryList = {
                        'tableTitle': '审核历史',
                        'tableContent': {
                            '审核级次': 'unitName',
                            '审核人': 'assignUser',
                            '审核人岗位': 'userTitle',
                            '通知时间': 'notifyTime',
                            '审核时间': 'completeTime',
                            '审核意见': 'opinion',
                        },
                        'tableData': getAuditHistory, //表格数据
                    }
                    params.tables = [this.lease ? contractList : contractList2, auditHistoryList]
                    // params.tables.push(contractList)
                    hideLoading()
                    return params

                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            exas(arg, this, requestFn, printData)
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },

        //基础库引入
        clickBaseImpot () {
            const DownRecursive = async (n1 = 0, n2 = 1) => {
                let res = await dataBaseRequest
                    .materialCategoryLibraryQueryListByParentClassId(n1, n2)
                    .then()
                console.log(res, 'hfadhi ')
                res.forEach(item => {
                    if (item.isDetailed === 0) {
                        DownRecursive(item.billId)
                    }
                    if (item.isDetailed === 1) {
                        this.curMaterialData = item
                    }
                })
            }
            DownRecursive() //向下递归 获取最子级
        },

        // 年计划引入
        clickYearNeedPlanImport () {
            planRequest.turnoverAnnualDemandPlanFindByBillId(this.basicForm.annualDemandPlanBillId).then(res=>{
                res.forEach(item=>{
                    item.uuid = getUuid()
                    item.children.forEach(v=>{
                        v.uuid = getUuid()
                        v.billId = this.billId
                        v.parentId = item.uuid
                        v.changeType = 1
                        v.oldState = 1
                    })
                })
                this.detailedTableData = res
            })
        },
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.curRow = row
            // row.amount =  row.demandQuantity * row.purchasePrice
            if(row.oldState != -1 ) {

                if(row.temporaryDemandPlanDtlId === '' || row.temporaryDemandPlanDtlId === null || !row.temporaryDemandPlanDtlId) {
                    this.curRow.changeType = 1
                    this.curRow.oldState = 1
                }else{
                    this.curRow.changeType = 2
                    this.curRow.oldState = 2
                }
                this.numYuan(row)

            }
        },
        //计算：建议租赁数*租赁单价*预计使用时间+建议采购数*采购单价+可调配数*采购单价=金额（元）
        numYuan (row) {
            if (this.isErrorMsg) {
                //判断是否为空
                console.log(row, 'row')
                if (!this.lease) {
                    if(row.quantityChanged != null && row.priceChanged != null) {
                        row.amountChanged = row.quantityChanged * row.priceChanged
                    }
                } else {
                    if(row.quantityChanged != null && row.priceChanged != null && row.leaseTimeChanged != null) {
                        //普通汇总
                        row.amountChanged = row.quantityChanged * row.priceChanged * row.leaseTimeChanged
                    }

                }

                this.collectCount()
                this.onTaxRate()
            }
        },
        //明细金额向上汇总到基础表单 不含税计划金额（元）
        collectCount () {
            this.basicForm.amountExcludingTax = 0
            this.detailedTableData.forEach(v => {

                const count = v.children.reduce(
                    (prev, c) => (prev += ( c.oldState !== -1 ? Number(c.amountChanged) || 0 : 0)),
                    0
                ).toFixed(2)

                this.basicForm.amountExcludingTax = count
                v.materialName = `小计： ${count}`

                if(this.basicForm.amountExcludingTax == 0) {
                    this.basicForm.amountChanged = 0
                }
            })
        },
        // 编辑的时候造历史修改数据结构
        // createHistory (row, e) {
        //     if (row.dtlId) {
        //         this.createHistoryData.push({
        //             historyId: '',
        //             modifedName: '',
        //             modifiedDate: '',
        //             modifiedId: '',
        //             opinion: '',
        //             sourceId: row.dtlId,
        //             sourceValue: 0,
        //             updateColumn: e, //修改字段
        //             updatedValue: row[e] //修改后的值
        //         })
        //     }
        //     this.numYuan(row) //计算金额
        // },

        //税率失去焦点的时候 计算 税额 = 不含税计划金额（元）*税率%
        onTaxRate () {
            if (
                this.basicForm.amountExcludingTax != 0 &&
                this.basicForm.taxRate != 0
            ) {
                this.basicForm.taxAmount =
          Number((this.basicForm.amountExcludingTax * this.basicForm.taxRate) / 100).toFixed(2)

                this.basicForm.amountChanged =
          (Number(this.basicForm.taxAmount) + Number(this.basicForm.amountExcludingTax)).toFixed(2)
            }
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject)=>{
                this.errorMsg = []
                if(this.detailedTableData.length > 0) {
                    this.detailedTableData.forEach(v => {
                        v.children.forEach((item, index)=>{
                            if (item.changeType !== -1) {
                                if (item.quantityChanged == null || item.quantityChanged == '') {
                                    let str = `请填写第 ${index + 1} 行的变更需求数量`
                                    this.errorMsg.push(str)
                                }

                                if (item.priceChanged == null || item.priceChanged == '') {
                                    let str = `请填写第 ${index + 1} 行的变更单价(元)`
                                    this.errorMsg.push(str)
                                }
                                if (this.lease) {
                                    if (item.leaseTimeChanged == null || item.leaseTimeChanged == '') {
                                        let str = `请填写第 ${index + 1} 行的租赁时间`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.startTimeChanged == null || item.startTimeChanged == '') {
                                        let str = `请填写第 ${
                                index + 1
                            } 行的变更开始使用时间`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.endTimeChanged === null || item.endTimeChanged === '') {
                                        let str = `请填写第 ${index + 1} 行的变更结束使用时间`
                                        this.errorMsg.push(str)
                                    }
                                }
                            }
                        })

                    })
                }else{
                    let str = '请添加明细'
                    this.errorMsg.push(str)
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()

                } else {
                    this.isErrorMsg = false

                    resolve()

                }

            })

        },
        audit () {
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                auditRequest.audit(auditParams).then(() => {
                    this.clientPop('suc', '审核成功')
                    this.getCurrentUnitInfo()
                    this.getAuditHistory()
                })
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },
        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/temporaryDemandPlanChanged/realDelete',
                    params: { id: this.billId },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },

        handleClose () {
            this.$router.go(-1)

        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
  color: red;
}

.like {
  color: rgb(46, 97, 215);
  font-size: 17px;
  line-height: 30px;
  cursor: pointer;
}
</style>
